package controllers

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"kukukaki/models"
	"log"
	"net/http"
	"time"
)

type request struct {
	Code string `json:"code"`
	UserInfo models.UserInfo  `json:"userinfo"`
}

type UserController struct {
	beego.Controller
}

type UserSession struct {
	Openid     string `json:"id"`
	UseNum     int    `json:"useNum"`
	WarningNum int    `json:"warningNum"`
	UseAmount  int    `json:"useAmount" `
}

type RespWXSmall struct {
	Openid     string `json:"openid"`      //用户唯一标识
	Sessionkey string `json:"session_key"` //会话密钥
	Unionid    string `json:"unionid"`     //用户在开放平台的唯一标识符，在满足 UnionID 下发条件的情况下会返回，详见 UnionID 机制说明。
	Errcode    int    `json:"errcode"`     //错误码
	ErrMsg     string `json:"errMsg"`      //错误信息
}

type loginresult struct {
	Sid string `json:"sid"`
	Err string `json:"err"`
	//us  UserSession
	//sys models.SystemCache
}

type sysusinfo struct {
	Us  UserSession  `json:"us"`
	Sys models.SystemCache `json:"sys"`
	Err string `json:"err"`
}

func loginWXSmall(code string) (wxInfo RespWXSmall, err error) {
	//https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
	appId := "wx7fe234f79ccff1e5"
	appSecret := "c4ee09d5bacf45cda49b3052d5ecf9e0"
	url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	resp, err := http.Get(fmt.Sprintf(url, appId, appSecret, code))
	if err != nil {
		return wxInfo, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &wxInfo)

	//err = tools.BindJson(resp.Body, &wxInfo)
	if err != nil {
		return wxInfo, err
	}
	if wxInfo.Errcode != 0 {
		return wxInfo, errors.New(fmt.Sprintf("code: %d, errmsg: %s", wxInfo.Errcode, wxInfo.ErrMsg))
	}
	return wxInfo, nil
}

func (c *UserController) Login() {
	us := c.GetSession("user")
	var re loginresult
	if us == nil {
		//无session
		var ob request
 
		json.Unmarshal(c.Ctx.Input.RequestBody, &ob)
	
	     //json.Unmarshal(c.Ctx.Input.RequestBody, &ob)
 
	    //fmt.Println("---o",ob)
 
		var code string = ob.Code
		var userinfo = ob.UserInfo
		
		if (code != "" && &userinfo !=nil) {
			
			respwx, err := loginWXSmall(code) //获取openid
			
			log.Println("Openid:" + respwx.Openid)
			//user := userinfo//models.UserInfo{}

			//err = json.Unmarshal([]byte(userinfo), &user)

			if err != nil {
				respwx.ErrMsg = err.Error()
				re = loginresult{Err:respwx.ErrMsg}
			} else {
				userinfo.Openid = respwx.Openid
				userinfo.SessionKey = respwx.Sessionkey

				u := models.UserInfo{Openid: userinfo.Openid}

				err = models.QueryUser(&u) //查询是否注册

				if u.RegisterTime == "" {
					//未注册
					userinfo.RegisterTime = time.Now().Format("2006-01-02 15:04:05")
					userinfo.LastLoginTime = userinfo.RegisterTime
					err = models.Register(&userinfo)
				}else{
					//更新登录时间
					u := models.UserInfo{Openid: userinfo.Openid,LastLoginTime:time.Now().Format("2006-01-02 15:04:05")}
					err = models.UpdateLoginTime(&u)
					if err != nil  {
						fmt.Println("-err-",err)
				 
					}
				}
				us = UserSession{Openid: userinfo.Openid, UseNum: userinfo.UseNumber, WarningNum: userinfo.RiskWarningNumber, UseAmount: userinfo.TheDayUseAmount}

				c.SetSession("user", us) //设置session

				log.Println("c.SessionRegenerateID():" + c.StartSession().SessionID())

				//re = result{sid: c.StartSession().SessionID(), us: us, sys: models.SysCache}
				re = loginresult{Sid: c.StartSession().SessionID()}
			}
		}else{
			re = loginresult{Err:"参数错误"}
		}
	} else {
		//session 有效
		re = loginresult{Sid: c.StartSession().SessionID()}

	}
	log.Println("~~~~~~~re:sid" + re.Sid +"  "+re.Err)
	c.Data["json"] = &re
	c.ServeJSON()
	return
}

func (c *UserController) Add() {

	var name string = c.GetString("name")
	var pwd string = c.GetString("pwd")
	log.Println("~~~~~~~name:" + name + "  pwd:" + pwd)
	//models.Register(name,pwd)

	c.Data["Website"] = name
	c.Data["Email"] = pwd
	c.TplName = "index.tpl"
}

func (c *UserController) Sysusinfo() {
	su := c.GetSession("user")
	var sui sysusinfo
	
	if su == nil {
		sui = sysusinfo{Err:"login"}
	}else {
		//session 有效
		 
		//u := models.UserInfo{Openid: su.(UserSession).Openid}
		//models.QueryUser(&u) 
		
		//us := UserSession{Openid: u.Openid, UseNum: u.UseNumber, WarningNum: u.RiskWarningNumber, UseAmount: u.TheDayUseAmount}
		sui = sysusinfo{ Us:su.(UserSession),Sys:models.SysCache }
	}
	
	log.Println("~~~~~~~err" + sui.Err)
	c.Data["json"] = &sui
	c.ServeJSON()
	return
}

func (c *UserController) Show() {
	c.Data["Website"] = "11111"
	c.Data["Email"] = "333333333"
	c.TplName = "index.tpl"
}
